package cn.wolfcode.business.service.impl;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import cn.wolfcode.business.domain.BpmnInfo;
import cn.wolfcode.business.domain.CarPackageAudit;
import cn.wolfcode.business.mapper.BpmnInfoMapper;
import cn.wolfcode.business.mapper.CarPackageAuditMapper;
import cn.wolfcode.business.vo.AuditInfoVO;
import cn.wolfcode.business.vo.AuditVO;
import cn.wolfcode.common.core.domain.entity.SysUser;
import cn.wolfcode.common.utils.DateUtils;
import cn.wolfcode.common.utils.SecurityUtils;
import cn.wolfcode.system.mapper.SysConfigMapper;
import cn.wolfcode.system.service.ISysConfigService;
import cn.wolfcode.system.service.ISysUserService;
import cn.wolfcode.system.service.impl.SysConfigServiceImpl;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.runtime.ProcessInstance;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import cn.wolfcode.business.mapper.ServiceItemMapper;
import cn.wolfcode.business.domain.ServiceItem;
import cn.wolfcode.business.service.IServiceItemService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

/**
 * 服务项Service业务层处理
 *
 * @author 白金之星
 * @date 2023-10-29
 */
@Service
@Transactional
public class ServiceItemServiceImpl implements IServiceItemService {
    @Autowired
    private ServiceItemMapper serviceItemMapper;
    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private ISysConfigService sysConfigService;
    @Autowired
    private BpmnInfoMapper bpmnInfoMapper;
    @Autowired
    private CarPackageAuditMapper carPackageAuditMapper;
    @Autowired
    private RuntimeService runtimeService;

    /**
     * 查询服务项
     *
     * @param id 服务项主键
     * @return 服务项
     */
    @Override
    public ServiceItem selectServiceItemById(Long id) {
        return serviceItemMapper.selectServiceItemById(id);
    }

    /**
     * 查询服务项列表
     *
     * @param serviceItem 服务项
     * @return 服务项
     */
    @Override
    public List<ServiceItem> selectServiceItemList(ServiceItem serviceItem) {
        return serviceItemMapper.selectServiceItemList(serviceItem);
    }

    /**
     * 新增服务项
     *
     * @param serviceItem 服务项
     * @return 结果
     */
    @Override
    public int insertServiceItem(ServiceItem serviceItem) {
        //参数校验
        if (serviceItem == null) {
            throw new RuntimeException("非法参数");
        }
        //判断折扣金额不能大于总金额
        int compare = serviceItem.getDiscountPrice().compareTo(serviceItem.getOriginalPrice());
        if (compare > 0) {
            throw new RuntimeException("折扣金额不能大于总金额");
        }
        //判断是否是套餐，是套餐为初始化状态，不是为无需审核
        if (ServiceItem.CARPACKAGE_YES.equals(serviceItem.getCarPackage())) {
            serviceItem.setAuditStatus(ServiceItem.AUDITSTATUS_INIT);
        } else {
            serviceItem.setAuditStatus(ServiceItem.AUDITSTATUS_NO_REQUIRED);
        }
        serviceItem.setCreateTime(DateUtils.getNowDate());
        return serviceItemMapper.insertServiceItem(serviceItem);
    }

    /**
     * 修改服务项
     *
     * @param serviceItem 服务项
     * @return 结果
     */
    @Override
    public int updateServiceItem(ServiceItem serviceItem) {
        //参数校验
        if (serviceItem == null) {
            throw new RuntimeException("非法参数");
        }
        //判断折扣金额不能大于总金额
        int compare = serviceItem.getDiscountPrice().compareTo(serviceItem.getOriginalPrice());
        if (compare > 0) {
            throw new RuntimeException("折扣金额不能大于总金额");
        }
        ServiceItem item = serviceItemMapper.selectServiceItemById(serviceItem.getId());
        //如果是上架或者是审核中状态, 抛出异常
        if (ServiceItem.SALESTATUS_ON.equals(item.getSaleStatus()) ||
                ServiceItem.AUDITSTATUS_AUDITING.equals(item.getAuditStatus())) {
            throw new RuntimeException("非法操作");
        }
        //套餐不能改成单项， 单项也不能改套餐
        if (!item.getCarPackage().equals(item.getAuditStatus())) {
            throw new RuntimeException("服务套餐与服务单项无法相互转换");
        }
        //判断状态时套参并且是审核通过的，改为初始化状态
        if (ServiceItem.CARPACKAGE_YES.equals(item.getCarPackage()) &&
                ServiceItem.AUDITSTATUS_APPROVED.equals(item.getAuditStatus())) {
            serviceItem.setAuditStatus(ServiceItem.AUDITSTATUS_INIT);
        }

        ServiceItem temp = new ServiceItem();
        BeanUtils.copyProperties(serviceItem,temp);
        return serviceItemMapper.updateServiceItem(temp);
    }

    /**
     * 批量删除服务项
     *
     * @param ids 需要删除的服务项主键
     * @return 结果
     */
    @Override
    public int deleteServiceItemByIds(Long[] ids) {
        return serviceItemMapper.deleteServiceItemByIds(ids);
    }

    /**
     * 删除服务项信息
     *
     * @param id 服务项主键
     * @return 结果
     */
    @Override
    public int deleteServiceItemById(Long id) {
        return serviceItemMapper.deleteServiceItemById(id);
    }

    @Override
    public void saleOn(Long id) {
        if (id == null) {
            throw new RuntimeException("非法参数");
        }
        ServiceItem item = serviceItemMapper.selectServiceItemById(id);
        if (item == null) {
            throw new RuntimeException("非法参数");
        }
        //判断是否是套餐
        if (ServiceItem.CARPACKAGE_YES.equals(item.getCarPackage()) &&
                !ServiceItem.AUDITSTATUS_APPROVED.equals(item.getAuditStatus())) {
            throw new RuntimeException("套餐必须通过审核才能上架");
        }
        //修改上架状态
        serviceItemMapper.updateSaleStatus(id, ServiceItem.SALESTATUS_ON);
    }

    /**
     * 下架服务
     *
     * @param id
     */
    @Override
    public void saleOff(Long id) {
        if (id == null) {
            throw new RuntimeException("非法参数");
        }
        ServiceItem item = serviceItemMapper.selectServiceItemById(id);
        if (item == null) {
            throw new RuntimeException("非法参数");
        }
        serviceItemMapper.updateSaleStatus(id, ServiceItem.SALESTATUS_OFF);
    }

    @Override
    public AuditInfoVO auditInfo(Long id) {
        //参数校验
        if (id == null) {
            throw new RuntimeException("非法参数");
        }
        ServiceItem serviceItem = serviceItemMapper.selectServiceItemById(id);
        if (serviceItem == null) {
            throw new RuntimeException("非法参数");
        }
        //判断是否是套餐
        if (!ServiceItem.CARPACKAGE_YES.equals(serviceItem.getCarPackage())) {
            throw new RuntimeException("必须是套餐才可以审核");
        }
        AuditInfoVO vo = new AuditInfoVO();
        //判断状态是否是初始化
        if (ServiceItem.AUDITSTATUS_INIT.equals(serviceItem.getAuditStatus()) ||
                ServiceItem.AUDITSTATUS_REPLY.equals(serviceItem.getAuditStatus())) {
            vo.setServiceItem(serviceItem);
            //查询店长信息
            List<SysUser> shopOwner = sysUserService.queryByRoleKey("shopOwner");
            vo.setShopOwners(shopOwner);
            //设置折扣金额
            String priceLimit = sysConfigService.selectConfigByKey("discountPriceLimit");
            if(!StringUtils.hasText(priceLimit)){
                priceLimit = "3000";
            }
            vo.setDiscountPrice(new BigDecimal(priceLimit));
            //查询财务信息
            if (serviceItem.getDiscountPrice().compareTo(new BigDecimal(priceLimit)) > 0) {
                List<SysUser> finance = sysUserService.queryByRoleKey("finance");
                vo.setFinances(finance);
            }
        } else {
            throw new RuntimeException("非法操作");
        }
        return vo;
    }

    @Override
    public void startAudit(AuditVO vo) {
        //参数校验
        if (vo == null) {
            throw new RuntimeException("参数异常");
        }
        ServiceItem serviceItem = serviceItemMapper.selectServiceItemById(vo.getId());
        if (serviceItem == null) {
            throw new RuntimeException("参数异常");
        }
        //判断是否是套餐
        if (!ServiceItem.CARPACKAGE_YES.equals(serviceItem.getCarPackage())) {
            throw new RuntimeException("必须是套餐才能审核");
        }
        //判断是否处于拒绝审核或者初始化
        if (ServiceItem.AUDITSTATUS_INIT.equals(serviceItem.getAuditStatus()) ||
                ServiceItem.AUDITSTATUS_REPLY.equals(serviceItem.getAuditStatus())) {
            //查询bpmn信息
            BpmnInfo bpmnInfo = bpmnInfoMapper.queryByType(CarPackageAudit.FLOW_AUDIT_TYPE);
            //创建 CarPackageAudit 保存到业务表中
            CarPackageAudit carPackageAudit = new CarPackageAudit();
            carPackageAudit.setCreatorId(SecurityUtils.getUserId().toString());
            carPackageAudit.setInfo(vo.getInfo());
            carPackageAudit.setServiceItemId(serviceItem.getId());
            carPackageAudit.setCreateTime(new Date());
            carPackageAudit.setServiceItemInfo(serviceItem.getInfo());
            carPackageAudit.setServiceItemName(serviceItem.getName());
            carPackageAudit.setServiceItemPrice(serviceItem.getDiscountPrice());
            carPackageAudit.setStatus(CarPackageAudit.STATUS_IN_ROGRESS);
            carPackageAuditMapper.insertCarPackageAudit(carPackageAudit);
            //设置流程变量
            HashMap<String, Object> map = new HashMap<>();
            map.put("shopOwnerId", vo.getShopOwnerId());
            if (vo.getFinanceId() != null) {
                map.put("financeId", vo.getFinanceId());
            }
            map.put("disCountPrice", serviceItem.getDiscountPrice().longValue());
            // 启动流程实例
            ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(bpmnInfo.getProcessDefinitionKey(),
                    carPackageAudit.getId().toString(), map);
            carPackageAudit.setInstanceId(processInstance.getId());
            carPackageAuditMapper.updateCarPackageAudit(carPackageAudit);
            // 修改单项状态为审核中状态
            serviceItemMapper.updateAuitStatus(vo.getId(), ServiceItem.AUDITSTATUS_AUDITING);
        } else {
            throw new RuntimeException("非法操作");
        }


    }
}
